package com.kd.juhaowan.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.flyjingfish.shapeimageviewlib.ShapeImageView;

import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.AuthInfoApi;
import com.kd.juhaowan.http.api.AuthLoginApi;
import com.kd.juhaowan.http.api.AutoLoginApi;
import com.kd.juhaowan.http.model.AuthInfoResult;
import com.kd.juhaowan.http.model.FollowResult;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.model.LoginUser;
import com.kd.juhaowan.utils.GlideHelper;
import com.kd.juhaowan.utils.LogUtil;
import com.kd.juhaowan.view.AutoLoginDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

public class AuthActivity extends BaseActivity {





    @BindView(R.id.activity_title)
    TextView titleView;
    @BindView(R.id.login_account_tip)
    TextView tipView;
    @BindView(R.id.login_account_content)
    TextView tip2View;
    @BindView(R.id.item_image)
    ShapeImageView imageView;
    private AuthInfoResult authInfoResult;

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        setData();
//    }


    @Override
    protected void reInitDate() {
        reInitDate();
    }

    private void setData(){
        List<LoginUser> infos = manager.readAllUserAccountInfo();
        if(infos!=null&&infos.size()>0){
            LoginUser user = infos.get(0);
            tipView.setText(user.getAccount());
        }
        EasyHttp.post(this).api(new AuthInfoApi(mUuid)).request(new HttpCallbackProxy<HttpData<AuthInfoResult>>(this){
            @Override
            public void onHttpSuccess(HttpData<AuthInfoResult> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                authInfoResult = result.getData();
                GlideHelper.loadGoodsCover(Glide.with(imageView),imageView,authInfoResult.getLogo_photo());
                tip2View.setText(authInfoResult.getDisplay_name()+"正在请求聚好玩手游APP授权登录，授权成功后可在聚好玩APP更好管理游戏账号");
            }

            @Override
            public void onHttpEnd(Call call) {
                super.onHttpEnd(call);

            }
        });
    }

    private void initDate(){
        List<LoginUser> infos = manager.readAllUserAccountInfo();
        if(infos!=null&&infos.size()>0){
            LoginUser user = infos.get(0);
            AutoLoginDialog dialog = new AutoLoginDialog(AuthActivity.this,user.getAccount());
            dialog.show();
            EasyHttp.post(this).api(new AutoLoginApi(user.getRefresh_token())).request(new HttpCallbackProxy<HttpData<LoginUser>>(this){
                @Override
                public void onHttpSuccess(HttpData<LoginUser> result, boolean cache) {
                    super.onHttpSuccess(result, cache);
                    LoginUser loginUser = result.getData();
//                        LogUtil.debugLog(result.getData().getAccess_token());
//                        Toast.makeText(AccountLoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                    user.setAccess_token(loginUser.getAccess_token());
                    user.setRefresh_token(loginUser.getRefresh_token());
                    manager.saveUserAccount(user);
                    manager.writeAutoLogin(true);
                    manager.writeLastLoginType(1);
                    manager.saveCurrentLoginUserTickit(user.getAccess_token());
                    setData();

                }

                @Override
                public void onHttpFail(Exception e) {
                    super.onHttpFail(e);
                    Intent intent =new Intent(AuthActivity.this,LoginAccountActivity.class);
                    intent.putExtra("isAuth",true);
                    register.launch(intent);
//                    startActivity(intent);
                }

                @Override
                public void onHttpEnd(Call call) {
                    super.onHttpEnd(call);
                    dialog.dismiss();
                }
            });
        }else{
            Intent intent =new Intent(AuthActivity.this,LoginAccountActivity.class);
            intent.putExtra("isAuth",true);
            register.launch(intent);
        }
    }
    private String mUuid;
    private ActivityResultLauncher<Intent> register;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleView.setText("授权登录");
        mUuid = getIntent().getStringExtra("uuid");
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                LogUtil.debugLog( "onActivityResult: _____" + result);
                if (result != null) {

                    if (result.getResultCode() == Activity.RESULT_OK) {
                        setData();

                    }
                }
            }
        });
        initDate();
    }
    @OnClick(R.id.login_confirm)
    public void onConfirmClick(){
        EasyHttp.post(this).api(new AuthLoginApi(mUuid)).request(new HttpCallbackProxy<HttpData<FollowResult>>(this){
            @Override
            public void onHttpSuccess(HttpData<FollowResult> result, boolean cache) {
                super.onHttpSuccess(result, cache);
                Intent in=new Intent();
                in.setAction("com.lysy.broad");
                in.putExtra("status",1);
                in.putExtra("code",result.getData().getToken());
//                in.putExtra("accessToken",result.getData().getAccess_token());
//                in.putExtra("refreshToken",result.getData().getRefresh_token());
                sendBroadcast(in);
                finish();
            }
        });





//        String text = feedbackEdit.getText().toString().trim();
//        if(TextUtils.isEmpty(text)){
//            ToastUtils.show("请输入内容");
//            return;
//        }
//        EasyHttp.post(this).api(new FeedbackApi(text)).request(new HttpCallbackProxy<HttpData<GameModel>>(this){
//            @Override
//            public void onHttpSuccess(HttpData<GameModel> result, boolean cache) {
//                super.onHttpSuccess(result, cache);
//                ToastUtils.show("反馈成功");
//                finish();
//            }
//        });
    }
    @OnClick({R.id.actvity_back,R.id.login_cancel})
    public void onBackClick(){
        Intent in=new Intent();
        in.setAction("com.lysy.broad");
        in.putExtra("status",0);
        sendBroadcast(in);
        finish();
    }


    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.activity_auth;
    }




}
